import 'package:boss/main.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/page/takeoutManagement/page/widget/double_formfield.dart';
import 'package:boss/ui/page/takeoutManagement/page/widget/plus_row.dart';
import 'package:boss/ui/widget/button/fixed_bottom_btn.dart';
import 'package:boss/ui/widget/loading/loading.dart';

import 'package:hi_common/hi_common.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class FullDecrementIndexPage extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<FullDecrementIndexPage> {
  List<dynamic> dataList = [
    {
      "fullAmount": null,
      "decreaseAmount": null,
      "id": DateTime.now().millisecondsSinceEpoch.toString(),
    }
  ];

  @override
  void initState() {
    super.initState();

    Future.delayed(Duration(milliseconds: 0), () async {
      obtainFullDecrement();
    });
  }

  //获取list数据
  obtainFullDecrement() async {
    showLoadingToast();
    try {
      final res = await api.fullDiscountQuery();

      if (!res.successful()) {
        toast(res.msg);
        return;
      }

      if (res.data == null || res.data.length == 0) {
        return;
      }

      dataList = [];
      res.data?.forEach((str) {
        dataList.add({
          "id": str["id"],
          "fullAmount": AmountUtil.price2String((str["fullAmount"] ?? 0)),
          "decreaseAmount": AmountUtil.price2String((str["decreaseAmount"] ?? 0)),
          "ctime": str["ctime"],
        });
      });

      setState(() {});
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  bool dotJudgment(num) {
    if (num.toString().split(".").length > 2) {
      return true;
    } else {
      return false;
    }
  }

  //保存更新
  fullDiscountUpdateFun(List fulllist) async {
    List<dynamic> newArr = [];

    var i = 0;
    for (var item in fulllist) {
      i++;
      if ((item["fullAmount"] == null || item["fullAmount"] == '') || (item["decreaseAmount"] == null || item["decreaseAmount"] == '')) {
        toast("表单填写不完整");
        return;
      }

      if (dotJudgment(item["fullAmount"]) || dotJudgment(item["decreaseAmount"])) {
        toast("第$i项钱数格式错误");
        return;
      }

      if (num.parse(item["fullAmount"].toString()) < num.parse(item["decreaseAmount"].toString())) {
        toast("第$i项减免价不能大于菜品与餐盒费用");
        return;
      }

      newArr.add({
        "fullAmount": (num.parse(item["fullAmount"]) * 100).toInt(),
        "decreaseAmount": (num.parse(item["decreaseAmount"]) * 100).toInt(),
      });
    }

    try {
      showLoadingToast();
      var res = await api.fullDiscountUpdate({
        'listFullDiscount': newArr ?? [],
      });
      if (res.successful()) {
        toast("保存成功");
        obtainFullDecrement();
      } else {
        toast(res.msg);
      }
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  plusRow() {
    var _key = DateTime.now().millisecondsSinceEpoch.toString();
    var repeatJudge = dataList.indexWhere((str) => str["ctime"] == _key);
    if (repeatJudge != -1) {
      return;
    }
    dataList.add({
      "fullAmount": null,
      "decreaseAmount": null,
      "id": _key,
    });
    setState(() {});
  }

  Widget headerText() {
    return Container(
      margin: EdgeInsets.only(
        top: 42.w,
      ),
      child: RichText(
        text: TextSpan(text: '满减规则', style: TextStyleConstant().normal_1_36, children: [
          WidgetSpan(
              child: SizedBox(
            width: 20.w,
          )),
          TextSpan(text: '例：满100减20', style: TextStyleConstant().normal_2_26)
        ]),
      ),
    );
  }

  Widget contentList() {
    return Column(
      children: (dataList ?? []).asMap().keys.map((index) {
        return FullDecrement(
          key: Key(dataList[index]["id"].toString()),
          data: dataList[index],
          onKmChanged: (v) {
            dataList[index]["fullAmount"] = v;
          },
          onPriceChanged: (v) {
            dataList[index]["decreaseAmount"] = v;
          },
          onDelete: () {
            dataList.removeAt(index);
            setState(() {});
          },
          enabled: true,
        );
      }).toList(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Expanded(
          child: SingleChildScrollView(
            padding: EdgeInsets.symmetric(horizontal: 30.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                headerText(),
                contentList(),
                PlusRow(onTap: plusRow),
              ],
            ),
          ),
        ),
        FixedBottomBtn(
          title: "保存",
          onTap: () async {
            fullDiscountUpdateFun(dataList);
          },
        ),
      ],
    );
  }
}

class FullDecrement extends StatelessWidget {
  final dynamic data;
  final ValueChanged<String> onKmChanged;
  final ValueChanged<String> onPriceChanged;
  final VoidCallback onDelete;
  final bool enabled;

  const FullDecrement({
    Key key,
    @required this.data,
    this.onKmChanged,
    this.onPriceChanged,
    this.onDelete,
    this.enabled,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DoubleFormField(
      itemHeight: 80,
      firstText: '菜品与餐盒满',
      secondText: '元,',
      thirdText: '减免订单',
      fourthText: '元',
      firstInputType: TextInputType.numberWithOptions(decimal: true),
      firstInputFormatters: [
        FilteringTextInputFormatter.allow(RegUtil.numberReg),
      ],
      secondInputType: TextInputType.numberWithOptions(decimal: true),
      secondInputFormatters: [
        FilteringTextInputFormatter.allow(RegUtil.numberReg),
      ],
      firstInitValue: "${(data["fullAmount"] == '' ? '' : data["fullAmount"] == null ? '' : data["fullAmount"] ?? '')}",
      secondInitValue: data["decreaseAmount"] == null ? null : (data["decreaseAmount"].toString() ?? ''),
      onFirstChanged: onKmChanged,
      onSecondChanged: onPriceChanged,
      onDelete: onDelete,
      firstMaxLength: 6,
      secondMaxLength: 6,
      enabled: enabled,
    );
  }
}
